package com.jieshuibao.controller;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jieshuibao.common.config.Global;
import com.jieshuibao.model.db.H5Spread;
import com.jieshuibao.model.db.H5SpreadExample;
import com.jieshuibao.model.db.H5SpreadExample.Criteria;
import com.jieshuibao.model.domain.SmsBean;
import com.jieshuibao.service.CoreService;
import com.jieshuibao.service.H5SpreadService;
import com.jieshuibao.service.RedisService;
import com.jieshuibao.util.ShortUuid;
import com.jieshuibao.util.StringUtils;
import com.jieshuibao.util.UUIDGenerator;
import com.jieshuibao.wx.h5.po.H5SpreadRes;
import com.jieshuibao.wx.util.WeiXinPublicUtil;

@Controller
@RequestMapping("/api")
public class H5SpreadController{
	
	private static final Logger log = Logger.getLogger(H5SpreadController.class);
	
	private int defaultPageSize=10;
	
	private String redirect = "redirect:/h5Spread/list.do";
	
	@Resource
	private H5SpreadService h5SpreadService;
	
	@Resource
	private RedisService redisService;
	
	@Resource
	private CoreService coreService;
	
	
/**
 * 根据openid 判断账号是否注册
 * @param openid
 * @return
 */
	@SuppressWarnings("static-access")
	@RequestMapping(value="/h5Spread/openid/{openid}",method=RequestMethod.POST)
	@ResponseBody
	public Object isExsit(@PathVariable String openid){
		H5SpreadRes res = new H5SpreadRes();
//		String openid = coreService.getOpenId(code, WeiXinPublicUtil.SRCMP);
		if(StringUtils.isEmpty(openid)){
			res.setCode(Global.FAIL);
			res.setDes("系统繁忙！");
			return res;
		}
		H5SpreadExample example = new H5SpreadExample();
		Criteria criteria = example.createCriteria();
		criteria.andOpenidEqualTo(openid);
		List<H5Spread> spreads = h5SpreadService.selectByExample(example );
		if(null != spreads && spreads.size()>0){
			String inviteCode = spreads.get(0).getInviteCode();
			res.setCode(res.REGISTERED);
			res.setInviteCode(inviteCode);
			res.setDes("已注册");
			return res;
		}else{
			res.setOpenid(openid);
			res.setCode(res.UNREGISTERED);
			res.setDes("未注册");
			return res;
		}
		
	}
	/**
	 * 根据手机号判断账号是否注册
	 * @param phone
	 * @return
	 */
	@RequestMapping(value="/h5Spread/phone/{phone}",method=RequestMethod.POST)
	@ResponseBody
	public Object isPhoneExsit(@PathVariable String phone){
		H5SpreadRes res = new H5SpreadRes();
		if(StringUtils.isEmpty(phone)){
			res.setCode(Global.FAIL);
			res.setDes("手机号为空！");
			return res;
		}
		H5Spread spread = h5SpreadService.getH5SpreadByPhone(phone);
		if(null != spread){
			res.setCode(Global.FAIL);
			res.setDes("该手机号已注册！");
			return res;
		}
		res.setCode(Global.SUCCESS);
		res.setDes("该手机号未注册！");
		return res;
	}
	/**
	 * 注册
	 * @param model
	 * @param h5Spread
	 * @param smsMessageSid   验证码id
	 * @param code            验证码
	 * @return
	 */
	@SuppressWarnings("static-access")
	@RequestMapping(value="/h5Spread/reg/{smsMessageSid}/{code}",method=RequestMethod.POST)
	@ResponseBody
	public Object add(Model model, @RequestBody H5Spread h5Spread,
			@PathVariable String smsMessageSid ,@PathVariable String code) {
		H5SpreadRes res = new H5SpreadRes();
		if(StringUtils.isEmpty(smsMessageSid)){
			res.setCode(Global.SYSTEMERROR);
			res.setDes("系统繁忙！");
			return res;
		}
		if(null == h5Spread){
			res.setCode(Global.FAIL);
			res.setDes("参数为空");
			return res;
		}
		String openid = h5Spread.getOpenid();
		if(StringUtils.isEmpty(openid)){
			res.setCode(Global.FAIL);
			res.setDes("系统繁忙");
			return res;
		}
		String phone = h5Spread.getPhone();
		if(StringUtils.isEmpty(phone)){
			res.setCode(Global.FAIL);
			res.setDes("手机号不能为空");
			return res;
		}
		if(!StringUtils.isMobile(phone)){
			res.setCode(Global.FAIL);
			res.setDes("手机号格式不正确!");
			return res;
		}
		if(StringUtils.isNotEmpty(phone)){
			H5Spread h5SpreadByPhone = h5SpreadService.getH5SpreadByPhone(phone);
			if(null != h5SpreadByPhone){
				res.setCode(res.REGISTERED);
				res.setDes("该手机号已注册!");
				return res;
			}
		}
		String pwd = h5Spread.getPassword();
		if(StringUtils.isEmpty(pwd)){
			res.setCode(Global.FAIL);
			res.setDes("密码不能为空!");
			return res;
		}
		SmsBean smsBean = redisService.getObejct(smsMessageSid,SmsBean.class);
		if(null == smsBean){
			res.setCode(Global.FAIL);
			res.setDes("验证码失效!");
			return res;
		}
		if(!smsBean.getCode().equalsIgnoreCase(code)){
			res.setCode(Global.FAIL);
			res.setDes("验证码错误!");
			return res;
		}
		redisService.delete(smsMessageSid);
		try {
			String inviteCode = ShortUuid.generateShortUuid();
			h5Spread.setCreateTime(new Date());
			h5Spread.setInviteCode(inviteCode);
			h5Spread.setPassword(pwd);
			h5SpreadService.addH5Spread(h5Spread);
			res.setCode(Global.SUCCESS);
			res.setInviteCode(inviteCode);
			res.setDes("注册成功");
		} catch (Exception e) {
			log.error(e);
			res.setCode(Global.SYSTEMERROR);
			res.setDes("系统繁忙");
		}
		return res;
	}
	/**
	 * 登录
	 * @param h5Spread
	 * @return
	 */
	@SuppressWarnings("static-access")
	@RequestMapping(value="/h5Spread/login" , method=RequestMethod.POST)
	@ResponseBody
	public Object login(@RequestBody H5Spread h5Spread){
		H5SpreadRes res = new H5SpreadRes();
		String phone = h5Spread.getPhone();
		if(StringUtils.isEmpty(phone)){
			res.setCode(Global.FAIL);
			res.setDes("手机号不能为空");
			return res;
		}
		if(!StringUtils.isMobile(phone)){
			res.setCode(Global.FAIL);
			res.setDes("手机号格式不正确!");
			return res;
		}
		H5Spread spread = h5SpreadService.getH5SpreadByPhone(phone);
		if(null == spread){
			res.setCode(res.UNREGISTERED);
			res.setDes("该手机号尚未注册!");
			return res;
		}
		String pwd = h5Spread.getPassword();
		if(StringUtils.isEmpty(pwd)){
			res.setCode(Global.FAIL);
			res.setDes("密码为空!");
			return res;
		}
		if(spread.getPassword().equalsIgnoreCase(pwd)){
			String cookieId = "TG"+UUIDGenerator.getUUID();
			redisService.setObject(cookieId, spread, 300);   //秒
			String inviteCode = spread.getInviteCode();
			res.setCode(Global.SUCCESS);
			res.setDes("登录成功!");
			res.setInviteCode(inviteCode );
			res.setCookieId(cookieId);
			return res;
		}else{
			res.setCode(Global.FAIL);
			res.setDes("账号或密码错误!");
			return res;
		}
	}
	/**
	 * 修改密码
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/updatePwd/{password}/{smsMessageSid}/{code}" , method = RequestMethod.POST)
	@ResponseBody
	public Object updatePwd(HttpServletRequest request,
			@PathVariable String smsMessageSid ,@PathVariable String code,@PathVariable String password){
		H5SpreadRes res = new H5SpreadRes();
		String cookieId = request.getHeader("cookieId");
		if(StringUtils.isEmpty(cookieId)){
			res.setCode(Global.SYSTEMERROR);
			res.setDes("系统繁忙!");
			return res;
		}
		H5Spread spread = redisService.getObejct(cookieId, H5Spread.class);
		if(null == spread){
			res.setCode(Global.NOTLOGIN);
			res.setDes("登录超时,请重新登录!");
			return res;
		}
		SmsBean smsBean = redisService.getObejct(smsMessageSid,SmsBean.class);
		if(null == smsBean){
			res.setCode(Global.FAIL);
			res.setDes("验证码失效!");
			return res;
		}
		if(!smsBean.getCode().equalsIgnoreCase(code)){
			res.setCode(Global.FAIL);
			res.setDes("验证码错误!");
			return res;
		}
		redisService.delete(smsMessageSid);
		spread.setPassword(password);
		h5SpreadService.updateH5Spread(spread);    //修改密码
		redisService.delete(cookieId);             //清除缓存账号信息
		res.setCode(Global.SUCCESS);
		res.setDes("修改成功！");
		return res;
	}
	/**
	 * 找回密码
	 * @param phone
	 * @param smsMessageSid
	 * @param code
	 * @param password            新密码
	 * @return
	 */
	@SuppressWarnings("static-access")
	@RequestMapping(value="/findPwd/{phone}/{password}/{smsMessageSid}/{code}" , method = RequestMethod.POST)
	@ResponseBody
	public Object findPwd(@PathVariable String phone,@PathVariable String smsMessageSid ,
			@PathVariable String code,@PathVariable String password){
		H5SpreadRes res = new H5SpreadRes();
		if(StringUtils.isEmpty(phone)){
			res.setCode(Global.FAIL);
			res.setDes("手机号不能为空");
			return res;
		}
		if(!StringUtils.isMobile(phone)){
			res.setCode(Global.FAIL);
			res.setDes("手机号格式不正确!");
			return res;
		}
		H5Spread spread = h5SpreadService.getH5SpreadByPhone(phone);
		if(null == spread){
			res.setCode(res.UNREGISTERED);
			res.setDes("该手机号尚未注册!");
			return res;
		}
		SmsBean smsBean = redisService.getObejct(smsMessageSid,SmsBean.class);
		if(null == smsBean){
			res.setCode(Global.FAIL);
			res.setDes("验证码失效!");
			return res;
		}
		if(!smsBean.getCode().equalsIgnoreCase(code)){
			res.setCode(Global.FAIL);
			res.setDes("验证码错误!");
			return res;
		}
		redisService.delete(smsMessageSid);
		spread.setPassword(password);
		h5SpreadService.updateH5Spread(spread);    //修改密码
		res.setCode(Global.SUCCESS);
		res.setDes("修改成功！");
		return res;
	}
}
